package com.wo.cloud.admin.controller;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.ObjectUtil;
import com.amazonaws.services.s3.model.PutObjectResult;
import com.amazonaws.services.s3.model.S3Object;
import com.wo.cloud.core.entity.Response;
import com.wo.cloud.oss.service.OssTemplate;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.Duration;

/**
 * @author liry
 * @version 1.0
 * @date Created on 2021/5/26 11:04
 * Description:
 */

@RestController
@RequestMapping("/test")
public class TestController {

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private OssTemplate ossTemplate;

    @GetMapping()
    public Response send() {

        String mobile = "13289316602";
        String code = "1188";
        redisTemplate.opsForValue().set("mate.sms.code." + mobile, code, Duration.ofMinutes(5));
        return Response.success("发送成功");
    }

    @PostMapping()
    public Response upload(@RequestParam("file") MultipartFile file) throws Exception {

        try {
            String bucketName = "dcc";
            PutObjectResult putObjectResult = ossTemplate.putObject(bucketName, file.getOriginalFilename(), file.getInputStream());
            if (ObjectUtil.isNotNull(putObjectResult)) {
                return Response.success();
            }
        } catch (Exception e) {
            new Throwable(e.getMessage());
        }
        return Response.fail();
    }

    // 获取文件链接等信息
    @GetMapping("/getFile")
    public Response getObject(@RequestParam String bucketName, @RequestParam String objectName){
        S3Object object = ossTemplate.getObject(bucketName, objectName);
        return Response.data(object);
    }

    // 下载文件
    @GetMapping("/download")
    @SneakyThrows
    public void download(@RequestParam String bucketName, @RequestParam String objectName, HttpServletRequest request, HttpServletResponse response){
        S3Object object = ossTemplate.getObject(bucketName, objectName);
        response.setContentType("application/octet-stream; charset=UTF-8");
        IoUtil.copy(object.getObjectContent(), response.getOutputStream());
    }

}
